<template>
  <div id="app-management" class="p-4">
    <!-- 顶部搜索栏 -->
    <a-form layout="inline" :model="searchParams" class="mb-4 search-form">
      <a-form-item label="应用名称">
        <a-input v-model:value="searchParams.appName" placeholder="请输入应用名称" allow-clear />
      </a-form-item>

      <a-form-item label="创建者">
        <a-input v-model:value="searchParams.userId" placeholder="输入用户ID" allow-clear />
      </a-form-item>

      <a-form-item v-if="false" label="生成类型">
        <a-select
          v-model:value="searchParams.codeGenType"
          placeholder="选择生成类型"
          style="width: 180px"
          allow-clear
        >
          <a-select-option value="multi_file">原生多文件模式</a-select-option>
          <a-select-option value="html">单文件模式</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button type="default" @click="handleReset">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <a-divider style="margin: 16px 0" />

    <!-- 表格 -->
    <div class="table-wrapper">
      <a-table
        class="management-table"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        row-key="id"
        bordered
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
        :loading="loading"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'cover'">
            <a-image v-if="record.cover" :src="record.cover" width="80" />
            <span v-else>无封面</span>
          </template>

          <template v-else-if="column.key === 'codeGenType'">
            <span>{{ record.codeGenType === 'multi_file' ? '原生多文件模式' : '单文件模式' }}</span>
          </template>

          <template v-else-if="column.key === 'priority'">
            <a-tag v-if="record.priority === 99" color="gold">精选</a-tag>
            <span v-else>{{ record.priority }}</span>
          </template>

          <template v-else-if="column.key === 'deployedTime'">
            {{
              record.deployedTime
                ? dayjs(record.deployedTime).format('YYYY-MM-DD HH:mm:ss')
                : '未部署'
            }}
          </template>

          <template v-else-if="column.key === 'userId'">
            <a-space>
              <a-avatar :src="record.user?.userAvatar || ''" />
              <span>{{ record.user?.userName || '未知' }}</span>
            </a-space>
          </template>

          <template v-else-if="column.key === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="handleEditApp(record)">编辑</a-button>
              <a-button v-if="record.priority === 99" size="small" @click="togglePriority(record)">
                取消精选
              </a-button>
              <a-button v-else size="small" @click="togglePriority(record)">精选</a-button>
              <a-popconfirm
                title="确认删除该应用吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="deleteApp(record.id)"
              >
                <a-button type="primary" danger size="small"><DeleteOutlined /></a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <!-- <div class="pagination-wrapper">
        <a-pagination
          v-model:current="pagination.current"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          show-size-changer
          show-quick-jumper
        />
      </div> -->
    </div>

    <AppEditModal
      :app="editApp"
      v-model:edit-loading="editLoading"
      v-model:openEditModal="openEditModal"
      @handle-edit-app="saveEditApp"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import type { TableColumnType } from 'ant-design-vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import {
  deleteAppByAdmin,
  getAppVoByAdmin,
  listAppVoByPageByAdmin,
  updateAppByAdmin,
} from '@/api/appController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import AppEditModal from '@/components/AppEditModal.vue'

// 表格列
const columns: TableColumnType[] = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 80, align: 'center' },
  { title: '应用名称', dataIndex: 'appName', key: 'appName', width: 150, align: 'center' },
  { title: '封面', key: 'cover', width: 100, align: 'center' },
  {
    title: '初始提示词',
    dataIndex: 'initPrompt',
    key: 'initPrompt',
    width: 120,
    ellipsis: true,
    align: 'center',
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    key: 'codeGenType',
    width: 120,
    align: 'center',
  },
  {
    title: '优先级',
    key: 'priority',
    width: 100,
    align: 'center',
  },
  {
    title: '部署时间',
    dataIndex: 'deployedTime',
    key: 'deployedTime',
    width: 120,
    align: 'center',
  },
  {
    title: '创建者',
    key: 'userId',
    width: 120,
    align: 'center',
  },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 120, align: 'center' },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200,
    align: 'center',
  },
]

const loginUserStore = useLoginUserStore()

const data = ref<API.AppVo[]>([])
const editApp = ref<API.AppVo>()
const openEditModal = ref<boolean>(false)
const editLoading = ref<boolean>(false)
const loading = ref<boolean>(false)

const total = ref<number | string>(0)
// 分页配置
// const pagination = reactive({
//   current: 1,
//   pageSize: 10,
//   total: data.value.length,
// })

const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    // showQuickJumper: true,
    showTotal: (total: number) => `共${total}条`,
  }
})
// 方法
const handleSearch = () => {
  searchParams.pageNum = 1
  getAppList()
  console.log(searchParams, 'searchParams')
}

const handleReset = () => {
  searchParams.pageNum = 1
  searchParams.pageSize = 10
  searchParams.appName = undefined
  searchParams.userId = undefined
  searchParams.codeGenType = undefined
  getAppList()
}

const getAppList = async () => {
  loading.value = true
  try {
    const res = await listAppVoByPageByAdmin({
      ...searchParams,
      sortField: 'createTime',
      sortOrder: 'desc',
    })
    console.log(res, 'ressearcj')
    if (res.data.code === 0 && res.data.data) {
      loading.value = false
      data.value = res.data.data.records || []
      total.value = res.data.data.totalRow || 0
    } else {
      loading.value = false
      message.error('获取应用列表失败' + res.data.message)
    }
  } catch (error) {
    loading.value = false
    console.log(error, '获取应用列表失败')
  }
}

const handleTableChange = (pagination: any) => {
  searchParams.pageNum = pagination.current
  searchParams.pageSize = pagination.pageSize
  getAppList()
}

const handleEditApp = (app: API.AppVo) => {
  editApp.value = app
  openEditModal.value = true
  console.log(app, 'app')
}

const saveEditApp = async (app: API.AppVo) => {
  try {
    const res = await updateAppByAdmin(app)

    if (res.data.code === 0 && res.data.data) {
      editLoading.value = false
      message.success('修改成功')
      openEditModal.value = false
      getAppList()
    } else {
      message.error('修改失败' + res.data.message)
    }
  } catch (error: any) {
    console.log(error, '修改失败')
    message.error('修改失败' + error.message)
  }
}

const togglePriority = async (app: API.AppVo) => {
  if (!app.id) return
  const newPriority = app.priority === 99 ? 0 : 99
  try {
    const res = await updateAppByAdmin({
      id: app.id,
      priority: newPriority,
    })

    if (res.data.code === 0 && res.data.data) {
      message.success(newPriority === 99 ? '设置精选成功' : '取消精选成功')
      getAppList()
    } else {
      message.error('设置精选失败' + res.data.message)
    }
  } catch (error: any) {
    console.log(error, '设置精选失败')
    message.error('设置精选失败' + error.message)
  }
}

const deleteApp = async (id: number) => {
  //   data.value = data.value.filter((item) => item.id !== id)
  //   pagination.total = total.value
  if (!id) return
  try {
    const res = await deleteAppByAdmin({ id })
    if (res.data.code === 0 && res.data.data) {
      message.success('删除成功')
      getAppList()
    } else {
      message.error('删除失败' + res.data.message)
    }
  } catch (error: any) {
    console.log(error, '删除失败')
    message.error('删除失败' + error.message)
  }
}

onMounted(() => {
  getAppList()
})
</script>

<style scoped>
#app-management {
  /* height: 100vh; */
  display: flex;
  flex-direction: column;
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background: #fff;
  padding: 20px 25px;
  margin: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  overflow-y: hidden;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.management-table {
  flex: 1;
  /* min-height: 100%; 即使没有数据也撑满 */
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

/* 响应式布局调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form :deep(.ant-form-item) {
    margin-right: 0;
    width: 100%;
  }

  #app-management {
    padding: 10px;
    margin: 5px;
  }
}
</style>
